#include<iostream>
#include<pthread.h>
#include<string>
#include<vector>
#include<functional>
#include<unistd.h>
#include<time.h>
using namespace std;

using func_t=function<void()>;    //函数包装器
const int threadnum = 5;

class ThreadDate
{
public:
    ThreadDate(const string &name,const uint64_t &ctime,func_t f)
        :threadname(name),createtime(ctime),func(f)
    {}
public:
    string threadname;
    uint64_t createtime;
    func_t func; //定义一个函数，线程执行
};


void Print()
{
    cout<<"我是线程的一部分任务"<<endl;
}

void*ThreadRountine(void*args)   //新线程
{
    int a=10;
    ThreadDate*td=static_cast<ThreadDate*>(args);

    while(1)
    {
        cout<<"新线程："<<"名字是"<<td->threadname<<"创建的时间："<<td->createtime<<endl;
        td->func();
        if(td->threadname=="thread-4")
        {
            cout<<td->threadname<<"触发了异常!!!"<<endl;
            //a/=10  //故意制作异常
        }
        sleep(3);
    }
}


//主线程
int main()
{
    vector<pthread_t> pthreads;  //线程数组
    for(int i=0;i<threadnum;i++)
    {
        char threadname[64];
        snprintf(threadname,sizeof(threadname),"%s-%lu","thread",i);

        pthread_t tid;
        ThreadDate*td=new ThreadDate(threadname,(uint64_t)time(nullptr),Print);
        pthread_create(&tid,nullptr,ThreadRountine,td);
        pthreads.push_back(tid);
        sleep(1);
    }

    cout<<"thread id:";
    for(auto tid:pthreads)
    {
        cout<<tid<<",";
    }
    cout<<endl;

    while(1)
    {
        cout<<"我是主线程"<<endl;
        sleep(3);
    }
    return 0;
}
